//
//  PlaneViewController.m
//  lv678
//
//  Created by apple on 15/6/11.
//  Copyright (c) 2015年 lampshade. All rights reserved.
//   飞机航班查询



#import "PlaneViewController.h"
#import "AFNetworking.h"
#import "CityListViewController.h"
#import "SqliteHelper.h"
#import "CalendarHomeViewController.h"
#import "CalendarViewController.h"
#import "Color.h"
#import "FlightListController.h"
#import "AFNetworking.h"
#import "CommonLoading.h"

@interface PlaneViewController ()
{
    CalendarHomeViewController *chvc;
    int isRoute;
}
- (IBAction)isRoute:(id)sender;//是否往返action
@property (weak, nonatomic) IBOutlet UIButton *offCityName;//出发城市名称
@property (weak, nonatomic) IBOutlet UIButton *arrCityName;//到达城市名称
@property (weak, nonatomic) IBOutlet UISegmentedControl *changeRoute;//segment
- (IBAction)city:(id)sender;//城市action
@property (weak, nonatomic) IBOutlet UIButton *offDate;//出发时间
@property (weak, nonatomic) IBOutlet UIButton *queryBtn;//查询按钮
@property (weak, nonatomic) IBOutlet UIView *calendarView;//日历视图
@property (weak, nonatomic) IBOutlet UILabel *arrTimeLabel;//到达时间标签
@property (weak, nonatomic) IBOutlet UIButton *arrTimeBtn;//到达时间按钮
@property (weak, nonatomic) IBOutlet UIImageView *changeCityName;//切换城市名称
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (strong, nonatomic)NSString *cityNames;
@property (nonatomic)int tagNum;
@property (nonatomic, strong)UILabel *label;
@property (nonatomic, weak)UIView *sheetView;

@property(nonatomic, strong)SqliteHelper *sqlite;


@end

@implementation PlaneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTableView];
    [self getData];

}
#pragma mark - 设置样式，获取数据
- (void)initTableView{
    [self.navigationController setNavigationBarHidden:NO animated:true];

    //隐藏到达时间
    _queryBtn.layer.cornerRadius = 6;
    _arrTimeLabel.alpha = 0;
    _arrTimeBtn.alpha = 0;
    
    //给按钮添加方法
    [_queryBtn addTarget:self action:@selector(submitInfo) forControlEvents:UIControlEventTouchUpInside];
    [_offDate addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventTouchUpInside];
    [_arrTimeBtn addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventTouchUpInside];
    
    //数据库操作
    SqliteHelper *dbHelp = [[SqliteHelper alloc]init];
    self.sqlite = dbHelp;
    
    //获取后两天的时间
   
    NSDate *current_Day = [NSDate date];
    NSDate *tommorow_Day = [NSDate dateWithTimeInterval:24*60*60*2 sinceDate:current_Day];
    
    [_offDate setTitle:[self currentSystemDate:current_Day] forState:UIControlStateNormal];
    [_arrTimeBtn setTitle:[self currentSystemDate:tommorow_Day] forState:UIControlStateNormal];
    [self change];
    
    //设置自定义Navigation
    UIColor *color = [UIColor whiteColor];
    NSDictionary *dict = [NSDictionary dictionaryWithObject:color forKey:NSForegroundColorAttributeName];
    [self.navigationController.navigationBar setTitleTextAttributes:dict];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"Navigation"] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
}

- (void)backToLast{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 进入controller之后开始从接口获取数据加载到数据库（PlaneCode.db）
- (void)getData{
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    if ([defaults objectForKey:@"LVFirstLanunch"] == nil) {

    NSString *path = [[NSBundle mainBundle]pathForResource:@"UrlList.plist" ofType:nil];
    NSDictionary *temp = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *url = [temp valueForKey:@"plane"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSDictionary *data = @{@"serviceName":@"SearchPortAll",@"queryParameters":@{}};
        [manager POST:url parameters:data success:^(AFHTTPRequestOperation *operation, id responseObject) {
                [_sqlite insertData:responseObject];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error%@",error);
        }];
    }
    [defaults setObject:@"1" forKey:@"LVFirstLanunch"];

}

#pragma mark - 通过设置alpha值来改变控件的显示隐藏
- (IBAction)isRoute:(id)sender {
    switch (_changeRoute.selectedSegmentIndex) {
        case 0:
            _arrTimeLabel.alpha = 0;
            _arrTimeBtn.alpha   = 0;
            isRoute = 0;
            break;
        case 1:
            _arrTimeBtn.alpha   = 1;
            _arrTimeLabel.alpha = 1;
            isRoute = 1;
        default:
            break;
    }
}
#pragma mark - 选择出发时间
- (void)selectDate:(UIButton *)btn{
    chvc                                              = [[CalendarHomeViewController alloc]init];
    [chvc setAirPlaneToDay:365 ToDateforString:nil];

    chvc.calendarblock                                = ^(CalendarDayModel *model){

//        NSLog(@"\n---------------------------");
//        NSLog(@"1星期 %@",[model getWeek]);
//        NSLog(@"2字符串 %@",[model toString]);
//        NSLog(@"3节日  %@",model.holiday);

        if (model.holiday) {

            [btn setTitle:[NSString stringWithFormat:@"%@",[model toString] ]forState:UIControlStateNormal];

        }else{

            [btn setTitle:[NSString stringWithFormat:@"%@ ",[model toString]] forState:UIControlStateNormal];

        }
    };

    [self.navigationController pushViewController:chvc animated:YES];
}

#pragma mark - 通过代理弹出城市列表
- (IBAction)city:(id)sender {
    _tagNum = [[sender valueForKey:@"tag"]intValue];
    CityListViewController *city = [[CityListViewController alloc] initWithNibName:@"CityListViewController" bundle:nil];
    city.delegate = self;
    city.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    [self presentViewController:city animated:YES completion:nil];
}

#pragma mark - 点击提交按钮请求服务器数据，并跳转界面
- (void)submitInfo{
    NSString *offDate = self.offDate.titleLabel.text;
    NSString *arrDate = self.arrTimeBtn.titleLabel.text;
    NSString *offCityCode = [_sqlite queryData:_offCityName.titleLabel.text];
    NSString *arrCityCode = [_sqlite queryData:_arrCityName.titleLabel.text];
    //    判断城市对应三字码是否存在，如果不存在这设置为空，防止程序崩溃
    if ([offCityCode isEqualToString:@""]) {
        offCityCode = @"";
    }
    if ([arrCityCode isEqualToString:@""]) {
        arrCityCode = @"";
    }
    if (isRoute == 1) {
        if (offDate >= arrDate) {
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:nil message:@"出发日期不能晚于返回日期" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alertView show];
        }else{
            NSDictionary *date = @{@"serviceName":@"searchFlight",@"queryParameters":@{@"startCode":offCityCode,@"endCode":arrCityCode,@"startDate":offDate}};
            FlightListController *flight = [[FlightListController alloc]init];
            flight.offName = _offCityName.titleLabel.text;
            flight.arrName = _arrCityName.titleLabel.text;
            flight.flightData = date;
            [self.navigationController pushViewController:flight animated:YES];
        }
    }else{
            NSDictionary *date = @{@"serviceName":@"searchFlight",@"queryParameters":@{@"startCode":offCityCode,@"endCode":arrCityCode,@"startDate":offDate}};
            FlightListController *flight = [[FlightListController alloc]init];
            flight.offName = _offCityName.titleLabel.text;
            flight.arrName = _arrCityName.titleLabel.text;
            flight.flightData = date;
            [self.navigationController pushViewController:flight animated:YES];
        
    }
}

#pragma mark - CityListViewController protocol 通过tag值来判断点击的是那个按钮，改变按钮的title
- (void)citySelectionUpdate:(NSString *)selectedCity{
    if (_tagNum == 100) {
        [_offCityName setTitle:selectedCity forState:UIControlStateNormal];
    }else{
        [_arrCityName setTitle:selectedCity forState:UIControlStateNormal];
    }
}
- (NSString *)getDefaultCity{
    return _offCityName.titleLabel.text;
}

#pragma mark - 获取系统当前时间
- (NSString *)currentSystemDate:(NSDate *)date{
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYY-MM-dd"];
    
    NSString *  locationString=[dateformatter stringFromDate:date];
    
    return locationString;}

#pragma mark - 使用手势调换两个城市的名称
- (void)change{
    self.changeCityName.userInteractionEnabled        = YES;
    UITapGestureRecognizer *recognizer                = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(changeCity)];
    recognizer.numberOfTapsRequired                   = 1;
    [self.changeCityName addGestureRecognizer:recognizer];
}
- (void)changeCity{
    NSString *cityNames                               = _offCityName.titleLabel.text;
    [_offCityName setTitle:_arrCityName.titleLabel.text forState:UIControlStateNormal];
    [_arrCityName setTitle:cityNames forState:UIControlStateNormal];
}
@end
